package com.lstoars.gifplus.sevlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lstoars.gifplus.domian.ImageDO;
import com.lstoars.gifplus.domian.TagDO;
import com.lstoars.gifplus.exception.ServiceException;
import com.lstoars.gifplus.result.PageResult;
import com.lstoars.gifplus.service.ImageService;

public class ViewListServlet extends HttpServlet {
	
	private ImageService imageService = null;
	
	private static final int PAGE_SIZE= 10;

	private static final long serialVersionUID = 4554447365920124900L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int pageNum = NumberUtils.toInt(req.getParameter("pageNum"), 1);
		int tagId = NumberUtils.toInt(req.getParameter("tagId"), 0);
		try {
			PageResult<List<ImageDO>>  result = imageService.queryImageList(pageNum,PAGE_SIZE, tagId);
			if(result.isSuccess()){
				//req.setAttribute("imageList", result.getValue());
				req.setAttribute("imageResult", result);
			}
			
			List<TagDO> tagList = imageService.queryTagList();
			req.setAttribute("tagList", tagList);
			
			RequestDispatcher dispatcher = req.getRequestDispatcher("/viewList.jsp");
			dispatcher.forward(req, resp);
		} catch (ServiceException e) {
			System.out.println(e);
			req.getRequestDispatcher("/error.jsp").forward(req, resp);
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
		imageService = (ImageService) context.getBean("imageService");
		super.init(config);
	}
	
}
